package com.kingsalert.kingsalert.fragment.ln_state;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.kingsalert.kingsalert.R;
import com.kingsalert.kingsalert.activity.ln.MainActivity;
import com.kingsalert.kingsalert.base.BaseLnFragment;
import com.kingsalert.kingsalert.bean.config.AppShowCustomize;
import com.kingsalert.kingsalert.bean.config.RecommendAppInfo;
import com.kingsalert.kingsalert.bean.process.ProcessInfo;
import com.kingsalert.kingsalert.config.UserState;
import com.kingsalert.kingsalert.dialog.CustomerServiceDialog;
import com.kingsalert.kingsalert.util.http.HttpUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LnStateFailFragment extends BaseLnFragment {

    private LinearLayout recommendAppListGroupLayout;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        page = "REJECT";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_ln_state_fail, container, false);

        SwipeRefreshLayout refreshLayout = view.findViewById(R.id.flsf_refreshlayout);
        TextView textView = view.findViewById(R.id.flsf_tv_text);

        view.findViewById(R.id.flsf_ib_customerservice).setOnClickListener(v -> new CustomerServiceDialog(getContext()).show());

        refreshLayout.setOnRefreshListener(() -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"REFRESH_CLICK","");
            HttpUtil.getInstance().userProcess(requireActivity(),
                () -> {
                    String state = ProcessInfo.getInstance().getUserState();
                    if (UserState.isStateChange(state)) {//刷新用户状态
                        FragmentActivity activity = requireActivity();
                        UserState.clearState();
                        activity.startActivity(new Intent(activity, MainActivity.class));
                        activity.finish();
                    }else HttpUtil.getInstance().requestAppSInfo(requireActivity(),this::refreshRecommendAppList);
                }
            );
            refreshLayout.setRefreshing(false);
        });

        String failDays = AppShowCustomize.getInstance().getRejectPeriod(requireContext());
        textView.setText(getString(R.string.ln_fail_text).replaceAll("xxx",failDays));

        recommendAppListGroupLayout = view.findViewById(R.id.flsf_layout_recommendapplist);

        refreshRecommendAppList();

        return view;
    }

    public void refreshRecommendAppList(){
        if (!AppShowCustomize.getInstance().getRecommendFlag()) return;
        recommendAppListGroupLayout.removeAllViews();
        ArrayList<RecommendAppInfo> recommendAppInfos = AppShowCustomize.getInstance().getRecommendAppList();
        for (RecommendAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp(recommendAppInfo);
        }
    }

    private void addRecommendApp(RecommendAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_recommend_app,null);

        TextView titleTv = itemView.findViewById(R.id.ira_tv_title);
        TextView textTv = itemView.findViewById(R.id.ira_tv_text);
        ImageView logoIv = itemView.findViewById(R.id.ira_iv_logo);
        TextView appNameTv = itemView.findViewById(R.id.ira_tv_appname);
        TextView amountTextTv = itemView.findViewById(R.id.ira_tv_amounttext);
        TextView scoreTv = itemView.findViewById(R.id.ira_tv_score);
        TextView downloadsTv = itemView.findViewById(R.id.ira_tv_downloads);

        titleTv.setText(recommendAppInfo.getTitle(requireContext()));
        textTv.setText(recommendAppInfo.getText(requireContext()));
        appNameTv.setText(recommendAppInfo.getAppName());
        amountTextTv.setText(recommendAppInfo.getAmountText());
        scoreTv.setText(recommendAppInfo.getScore());
        downloadsTv.setText(recommendAppInfo.getDownloads());

        //Install按键
        itemView.findViewById(R.id.ira_btn_install).setOnClickListener(v -> {
            HttpUtil.getInstance().saveBuriedPoint(page,"RECOMMEND_"+recommendAppInfo.getAppName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getPath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogoBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getLogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLogoBitmap(bitmap);
                        new Handler(Looper.getMainLooper()).post(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(recommendAppInfo.getLogoBitmap());

        recommendAppListGroupLayout.addView(itemView);
    }





}